package com.truongnha.clienttn.presentation.fragment;

import java.util.ArrayList;
import java.util.List;

import com.truongnha.clienttn.R;
import com.truongnha.clienttn.business.model.ASubjectMarkModel;
import com.truongnha.clienttn.business.service.StudentMarkService;
import com.truongnha.clienttn.presentation.CheckNetwork;
import com.truongnha.clienttn.presentation.adapter.StudentMarkAdapter;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;

public class StudentMarkFragment extends Fragment {

	private Intent doneLoading;
	private List<ASubjectMarkModel> list = new ArrayList<ASubjectMarkModel>();
	private StudentMarkAdapter studentMarkAdapter;

	private ListView grid;
	private LinearLayout alert;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.student_mark_template, container,
				false);
		new getAttendanceTask().execute();
		grid = (ListView) view.findViewById(R.id.mark_grid);
		alert = (LinearLayout) view.findViewById(R.id.alertLinearLayout);
		if (!CheckNetwork.isAvailable(true))
			alert.setVisibility(1);

		studentMarkAdapter = new StudentMarkAdapter(getActivity(), list);
		grid.setAdapter(studentMarkAdapter);

		return view;
	}

	class getAttendanceTask extends AsyncTask<String, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			doneLoading = new Intent();
			doneLoading.setAction("DONE_LOADING_ACTION");
			doneLoading.putExtra("doneLoading", false);
			getActivity().getApplicationContext().sendBroadcast(doneLoading);
		}

		@Override
		protected Void doInBackground(String... params) {
			list.clear();
			StudentMarkService studentMarkService = new StudentMarkService(
					getActivity().getApplicationContext());
			if (CheckNetwork.isAvailable(true))
				studentMarkService.getMarkFromServer();

			studentMarkService.getMarkFromData(list);
			Log.d("log", "after get attend  size :" + list.size());
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			// Broadcast to main activity when done loading
			doneLoading = new Intent();
			doneLoading.setAction("DONE_LOADING_ACTION");
			doneLoading.putExtra("doneLoading", true);
			getActivity().getApplicationContext().sendBroadcast(doneLoading);
			studentMarkAdapter.notifyDataSetChanged();
			// grid.smoothScrollToPosition(list.size());
		}
	}// End class getTermTask

}